﻿﻿using System;
using StarTrek.Ship;
using StarTrek.World;

namespace StarTrek.Weapon
{
    class Phaser:iWeapon
    {
        private float effectiveness;
        private float OptimumRange;
        private string name;
        private iShip parent;
        private bool damaged;

        public Phaser(string Name, float efficiency, float Range)
        {
            // 0 sucks, 1 is the best.
            effectiveness = efficiency;
            OptimumRange = Range;
            name = Name;
        }
        public Phaser() {}
        #region iWepon Members

        public ShipStatus ApplyWeponToShip(iShip Target, float Enegery)
        {
            ShipStatus rVal = null;
            float dis = Parent.CurrentLocation.CalculateDistance(Target.CurrentLocation);
            //TODO: Fix Dispursion Alg, firing one unit of engery at optimum range should do one unit of damage.
            // if we are 90% of optimu range we should do 110% and if we are at 110% range we should do 90% damage
            float RangeDispursion = (dis / OptimumRange );
            float totalDamage = Enegery*effectiveness*RangeDispursion;

            if (totalDamage > 0)
            {
                Target.ApplyDamage(totalDamage);
                rVal = Target.CreateShipStatus();
            }
            System.Diagnostics.Debug.Write(String.Format("Applying {0} units of damage to {1}", Enegery * effectiveness * RangeDispursion,Target.ShipName));
            return rVal;
        }

        public iShip ApplyDefenseToShip(float Energy)
        {
            throw new InvalidWeaponException(this, this.parent);
        }

        public iShip Parent
        {
            get
            {
                return parent;
            }
            set
            {
                parent = value;
            }
        }

        public bool isFunctional
        {
            get
            {
                return !damaged;
            }
            set
            {
                damaged = !value;
            }
        }

        #endregion

        #region iWeapon Members


        public string WeaponReport()
        {
            return string.Format("Ship has {0} units of power remaining.", parent.PowerUnit);
        }

        #endregion

        #region iWeapon Members


        public void Load(System.Xml.XmlNode node)
        {

            // 0 sucks, 1 is the best.
            effectiveness = Convert.ToSingle(node.Attributes["Eff"].Value);
            OptimumRange = Convert.ToSingle(node.Attributes["Range"].Value);
            name = node.Attributes["Name"].Value;
        }

        public bool isOffensive { get { return true; } }
        public bool NeedsEnegery { get { return true; } } 
        public string Name {get { return name;}}
        #endregion
    }
}
